﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight;
using MODEL;
using Service;
using Microsoft.Practices.ServiceLocation;
using GalaSoft.MvvmLight.Views;
using System.Windows.Input;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Ioc;
using Common;

namespace ViewModel.AlertCreate
{
    public class AlertMakeViewModel : ViewModelBase
    {
        private IAlertMakeService m_AlertMakeService;

        private List<AlertMakeInfo> m_AlertMakeInfos;
        public List<AlertMakeInfo> AlertMakeInfos
        {
            get { return this.m_AlertMakeInfos; }
            set { this.m_AlertMakeInfos = value; base.RaisePropertyChanged(() => this.AlertMakeInfos); }
        }
        
        public ICommand NormalAlertCommand { get; set; }
        public ICommand ChooseAlertTypeCommand { get; set; }
        public ICommand ShowAlertDetailCommand { get; set; }
        public ICommand InsertAlertCommand { get; set; }
        public ICommand UpdateAlertCommand { get; set; }
        public ICommand DeleteAlertCommand { get; set; }
        public ICommand BatchDeleteAlertCommand { get; set; }
        
        public AlertMakeViewModel(IAlertMakeService alertMakeService)
        {
            
            this.m_AlertMakeService = alertMakeService;

            NormalAlertCommand = new RelayCommand(ShowMessageReleaseDialog);
            ChooseAlertTypeCommand = new RelayCommand(() => MessengerInstance.Send<object>(null, "AlertCreate_ShowChooseAlertTypeDialog"));
            InsertAlertCommand = new RelayCommand(ShowInsertAlertForm);
            UpdateAlertCommand = new RelayCommand<AlertMakeInfo>(ShowUpdateAlertForm);
            DeleteAlertCommand = new RelayCommand<AlertMakeInfo>(DeleteAlert);
            BatchDeleteAlertCommand = new RelayCommand(BatchDeleteAlert);
            ShowAlertDetailCommand = new RelayCommand<AlertMakeInfo>(ShowAlertDetailInfo);

            RefreshData();
        }

        public async void RefreshData(Action AfterRefreshAction = null)
        {
            try
            {
                if (AppSetting.Instance.User.role.IsAdmin)
                {
                    this.AlertMakeInfos = (await this.m_AlertMakeService.GetAlertMakeInfosAsync()).ToList();
                }
                else
                {
                    this.AlertMakeInfos = (await this.m_AlertMakeService.GetAlertMakeInfosAsync(AppSetting.Instance.User.UserId)).ToList();
                }
            }
            catch (Exception ex)
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowError("加载数据失败", "错误", "确定", null);
                Log.WriteException(ex);
            }
        }

        private void ShowInsertAlertForm()
        {
            IStationServcie stationServcie = ServiceLocator.Current.GetInstance<IStationServcie>();
            IElementService elemenetService = ServiceLocator.Current.GetInstance<IElementService>();

            AlertMakeEditViewModel alertMakeEditViewModel = new AlertMakeEditViewModel(this.m_AlertMakeService, stationServcie, elemenetService) { ParentViewModel = this};
            this.MessengerInstance.Send<ViewModelBase>(alertMakeEditViewModel, "AlertCreate_ShowAlertEditForm");
        }

        private void ShowMessageReleaseDialog()
        {         
            MessageRelease.MessageReleaseViewModel vm = SimpleIoc.Default.GetInstanceWithoutCaching<MessageRelease.MessageReleaseViewModel>();
            this.MessengerInstance.Send<ViewModelBase>(vm, "AlertCreate_ShowMessageReleaseDialog");
        }

        private void ShowUpdateAlertForm(AlertMakeInfo alertMakeInfo)
        {
            IStationServcie stationServcie = ServiceLocator.Current.GetInstance<IStationServcie>();
            IElementService elemenetService = ServiceLocator.Current.GetInstance<IElementService>();

            AlertMakeEditViewModel alertMakeEditViewModel = new AlertMakeEditViewModel(this.m_AlertMakeService, stationServcie, elemenetService) { AlertMakeInfo = alertMakeInfo,ParentViewModel = this };
           
            this.MessengerInstance.Send<ViewModelBase>(alertMakeEditViewModel, "AlertCreate_ShowAlertEditForm");
        }

        private async void DeleteAlert(AlertMakeInfo alertMakeInfo)
        {

            try
            {
                bool IsConfirm = await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("当前数据即将被删除，是否确认？", "提示", "确认", "取消", null);
                if (!IsConfirm)
                {
                    return;
                }
                Task task = this.m_AlertMakeService.DeleteAlertMakeInfo(new List<string> { alertMakeInfo.Id });
                task.Wait();
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("删除成功", "提示");
                RefreshData();
            }
            catch (Exception ex)
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowError("删除失败", "错误", "确定", null);
                Log.WriteException(ex);
            }       
        }

        private async void BatchDeleteAlert()
        {           
            try
            {
                List<AlertMakeInfo> selectedAlertInfos = AlertMakeInfos.Where(alertInfo => alertInfo.IsChecked).ToList();
                if (!selectedAlertInfos.SafeCheck())
                {
                    await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("未选中任何数据", "提示");
                    return;
                }

                bool isComfirm = await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("所选数据将被全部删除，是否确认？", "提示", "确认", "取消", null);
                if (!isComfirm)
                {
                    return;
                }
                Task task = this.m_AlertMakeService.DeleteAlertMakeInfo(selectedAlertInfos.Select(alertInfo => alertInfo.Id).ToList());
                task.Wait();
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("删除成功", "提示");
                RefreshData();
            }
            catch (Exception ex)
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowError("删除失败", "错误", "确定", null);
                Log.WriteException(ex);
            }          
        }

        private bool CanBatchDelete()
        {
            return AlertMakeInfos.Any(alertInfo => alertInfo.IsChecked);
        }


        private void ShowAlertDetailInfo(AlertMakeInfo alertMakeInfoViewModel)
        {
            MessengerInstance.Send(alertMakeInfoViewModel, "AlertCreate_ShowAlertDetailForm");
        }
    }
}
